#conding=utf-8
import pickle
import getpass

def open_database():
	try:
		with open('passwd.pkl','rb') as f:
			return pickle.load(f)
	except IOError as e:
		return False
	except Exception as e:
		raise e


def updata_database(user_data):
	try:
		with open('passwd.pkl','wb') as f:
			pickle.dump(user_data,f)
			return True
	except IOError as e:
		return False
	except Exception as e:
		raise e


def register():
	username=input('please input your id:')
	user_data=open_database() if open_database() else {}
	if username in user_data.keys():
		print('user alread exists')
		return False
	user_passwd=getpass.getpass('please input your password:')
	user_data[username]=user_passwd
	db_sataus=updata_database(user_data)
	if not db_sataus:
		print('register failed!')
	print('register successfully!')


def login():
	count = 0
	
	username=input('please input your id:')
	user_data=open_database()
	passwd=user_data.get(username)
	if passwd is None:
		print('user does not exists')
		return False
	while count < 3:
		user_passwd=getpass.getpass('please input your password:')
		if user_passwd!=passwd:
			count += 1
			print('password error,at last 3 times!')
			continue
		print('password confirm')
		break
	else:
		print('opration failed!')


def main():
	while True:
		user_choice = input('1 register ,2 login ,0 exit')
		if user_choice == '1':
			register()
		elif user_choice=='2':
			login()
		else:
			break
if __name__ == '__main__':
	main()